<template>
  <div class="panel-tab__content">
    <el-button type="primary" @click="openButtonConfig">选择按钮</el-button>
    <div class="button-table">
        <el-table :data="buttonConfigList" size="mini" max-height="240" border fit style="flex: none">
            <el-table-column label="名称"  prop="label" />
            <el-table-column label="编码"  prop="value" />
            <el-table-column label="排序"  prop="sort" />
            <el-table-column label="操作">
                <template slot-scope="{ row, $index }">
                    <el-button size="mini" type="text" @click="detailButton(row, $index)">修改</el-button>
                    <el-divider direction="vertical" />
                    <el-button size="mini" type="text" style="color: #ff4d4f" @click="delButton(row, $index)">删除</el-button>
                </template>
            </el-table-column>
      </el-table>
    </div>
    <el-dialog title="选择常用按钮" :visible.sync="dialogTable" destroy-on-close>
         <el-table :data="dialogTableList" size="mini" max-height="240" border fit style="flex: none" @selection-change="handleSelectionChange" v-loading="dialogTableLoading" ref="selectTable">
            <el-table-column type="selection" width="55" />
            <el-table-column label="名称"  prop="label" />
            <el-table-column label="编码"  prop="value" />
            <el-table-column label="排序"  prop="sort" />
        </el-table>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogTable = false">取 消</el-button>
            <el-button type="primary" @click="saveButton">确 定</el-button>
        </span>
    </el-dialog>
    <el-dialog title="编辑按钮" :visible.sync="editButton" width="500px">
        <el-form :model="buttonForm" :rules="rules" ref="buttonFormRef" label-width="100px" >
            <el-form-item label="名称" prop="label">
                <el-input v-model="buttonForm.label"></el-input>
            </el-form-item>
            <el-form-item label="编码" prop="value">
                <el-input v-model="buttonForm.value" disabled></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
                <el-input-number v-model="buttonForm.sort" :min="0" :max="3"></el-input-number>
            </el-form-item>
        </el-form>
        <template slot="footer">
            <el-button size="mini" @click="editButton = false">取 消</el-button>
            <el-button size="mini" type="primary" @click="saveEditButton">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { buttonList } from "@/api/bpm/model";
export default {
    name: 'ElementButtonConfig',
    props: {
        businessObject: Object,
        id: String,
        type: String
    },
    inject: {
        prefix: "prefix",
        width: "width"
    },
    data() {
        return {
            buttonConfigList: [],
            dialogTable: false,
            editingPropertyIndex: -1,
            dialogTableList: [],
            multipleSelection: [],  //选中的按钮
            editButton: false,
            buttonForm: {
                label: '',
                value: '',
                sort: ''
            },
            dialogTableLoading: false,
            rules: {
                label: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                ],
                value: [
                    { required: true, message: '请输入编码', trigger: 'blur' },
                ],
                sort: [
                    { required: true, trigger: 'blur' },
                ],
            }
        }
    },
    watch: {
         id: {
            immediate: true,
            handler(val) {
                val && val.length && this.resetAttributesList();
            }
        }
    },
    created() {
        this.getButtonList();
    },
    methods: {
         resetAttributesList() {
            this.bpmnElement = window.bpmnInstances.bpmnElement;
            this.otherExtensionList = []; // 其他扩展配置
            this.bpmnElementProperties =
                this.bpmnElement.businessObject?.extensionElements?.values?.filter(ex => {
                if (ex.$type !== `${this.prefix}:Buttons`) {
                    this.otherExtensionList.push(ex);
                }
                return ex.$type === `${this.prefix}:Buttons`;
                }) ?? [];
            const data = this.bpmnElementProperties.reduce((pre, current) => pre.concat(current.values), []);
            if(data[0] != undefined){
                data.sort(this.compare('sort')) // 根据sort排序
                // 保存所有的 扩展属性字段
                this.bpmnElementPropertyList = data
                // 复制 显示
                this.buttonConfigList = JSON.parse(JSON.stringify(this.bpmnElementPropertyList ?? []));
            }else{
                 this.bpmnElementPropertyList = []
                 this.buttonConfigList = []
            }
        },
        compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value1 - value2;
            }
        },
        getButtonList() {
            this.dialogTableLoading = true
            buttonList().then((res) => {
                if(res.code === 0){
                    this.dialogTableLoading = false
                    this.dialogTableList = res.data
                }
            })
        },
        openButtonConfig() {
            this.dialogTable = true
            let rows = []
            for (let m = 0; m < this.buttonConfigList.length; m++) {
                for (let n = 0; n < this.dialogTableList.length; n++) {
                    if (this.buttonConfigList[m].value === this.dialogTableList[n].value) {
                            rows.push(this.dialogTableList[n])
                    }
                }
            }
            if(rows){
                this.$nextTick(()=>{
                    rows.forEach(row => {
                        if(this.$refs.selectTable) this.$refs.selectTable.toggleRowSelection(row,true)
                    })
                })
            }else{
                if(this.$refs.selectTable) this.$refs.selectTable.clearSelection(row,true)
            }
        },
        detailButton(attr, index) {
            this.editingPropertyIndex = index;
            this.buttonForm = JSON.parse(JSON.stringify(attr));
            this.editButton = true;
            this.$nextTick(() => {
                if (this.$refs["buttonFormRef"]) this.$refs["buttonFormRef"].clearValidate();
            });
        },
        delButton(attr, index) {
            this.$confirm("是否确认删除该按钮?", "提示", {
                confirmButtonText: "确 认",
                cancelButtonText: "取 消"
            })
            .then(() => {
                this.buttonConfigList.splice(index, 1);
                this.bpmnElementPropertyList.splice(index, 1);
                // 新建一个属性字段的保存列表
                const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Buttons`, {
                    values: this.bpmnElementPropertyList
                });
                this.updateElementExtensions(propertiesObject);
                this.resetAttributesList();
            })
            .catch(() => console.info("操作取消"));
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        /* 修改按钮 */
        saveEditButton() {
            this.$refs["buttonFormRef"].validate(valid => {
                if (valid) {
                    const { label, value, sort } = this.buttonForm
                    this.editButton = false
                     window.bpmnInstances.modeling.updateModdleProperties(this.bpmnElement, this.bpmnElementPropertyList[this.editingPropertyIndex], {
                       label, value, sort
                    });
                    this.resetAttributesList();
                }
            })
        },
        getArrDifference (arr1, arr2) {
            return arr1.concat(arr2).filter(function (v, i, arr) {
                return arr.indexOf(v) === arr.lastIndexOf(v)
            })
        },
        getArrEqual (arr1, arr2) {
            let newArr = []
            for (let i = 0; i < arr2.length; i++) {
                for (let j = 0; j < arr1.length; j++) {
                if (arr1[j] === arr2[i]) {
                    newArr.push(arr1[j])
                }
                }
            }
            return newArr
        },
        /* 选择常用按钮 */
        saveButton() {
            let conmmonObj = []
            let diffVObj = []
            //选中的跟列表的对比 相同的 拿列表的数据
            let multipleData = this.multipleSelection.map(item => item.value);
            let tableData = this.bpmnElementPropertyList.map(item => item.value)
            let commonList = this.getArrEqual(multipleData,tableData)
            let diffList = this.getArrDifference(multipleData,tableData)
            this.multipleSelection.map((item) => {
                this.bpmnElementPropertyList.map((val) => {
                    if(item.value == val.value){
                       conmmonObj.push(val) 
                    }
                })
            })
            // 不同的zhi 
            if(!tableData.includes(diffList)){ //table 不存在
               diffList.map((item)=> {
                   this.multipleSelection.map((val) => {
                       if(val.value == item){
                           const { label, value, sort} = val;
                           const data = window.bpmnInstances.moddle.create(`${this.prefix}:ButtonTy`, { label, value, sort});
                           diffVObj.push(data)
                       }
                   })
               })
            }
            const propertiesObject = window.bpmnInstances.moddle.create(`${this.prefix}:Buttons`, {
                values:  diffVObj.concat(conmmonObj)
            });
            this.updateElementExtensions(propertiesObject);
            this.dialogTable = false;
            this.resetAttributesList();
        },
         updateElementExtensions(properties) {
            const extensions = window.bpmnInstances.moddle.create("bpmn:ExtensionElements", {
                values: this.otherExtensionList.concat([properties])
            });
            window.bpmnInstances.modeling.updateProperties(this.bpmnElement, {
                extensionElements: extensions
                });
            }
    },

}
</script>